package com.yn.confirm;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.yn.thread.MQCustomerThread;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @ClassName: Customer
 * @Description:
 * @author: 王胜
 * @date 2021/7/11
 * @Version: 1.0
 **/
public class Customer {
    public static void main(String[] args) throws Exception {
        releaseConfirmationAsync();
    }
    public static void singleReleaseConfirmation() throws Exception {
        Connection connection= new ConnectionFactory().newConnection();
        Channel chanel = connection.createChannel();
        chanel.confirmSelect();
        chanel.queueDeclare("queue",false,false,true,null);
        long start = System.currentTimeMillis();
        for (int i = 0; i < 1000; i++) {
            chanel.basicPublish("","",null,("messages"+i).getBytes());
            boolean confirms = chanel.waitForConfirms();
            if(confirms){
                System.out.println("消息"+i+"发送成功");
            }
        }
        long end = System.currentTimeMillis();
        System.out.println("单个确认使用时间："+(end-start));
    }
    public static void batchReleaseConfirmation() throws Exception {
        Connection connection= new ConnectionFactory().newConnection();
        Channel chanel = connection.createChannel();
        chanel.confirmSelect();
        chanel.queueDeclare("queue",false,false,true,null);
        long start = System.currentTimeMillis();
        for (int i = 0; i < 1000; i++) {
            chanel.basicPublish("","",null,("messages"+i).getBytes());
            if(i%100==0){
                chanel.waitForConfirms();
                System.out.println("消息"+i+"发送成功");
            }
        }
        long end = System.currentTimeMillis();
        System.out.println("批量确认使用时间："+(end-start));
    }
    public static void releaseConfirmationAsync() throws Exception {
        Connection connection= new ConnectionFactory().newConnection();
        Channel chanel = connection.createChannel();
        chanel.confirmSelect();
        chanel.queueDeclare("queue",false,false,true,null);
        long start = System.currentTimeMillis();
        chanel.addConfirmListener(( deliveryTag,  multiple)->{
                    System.out.println("确认"+deliveryTag);
                },
                ( deliveryTag,  multiple)->{
                    System.out.println("未确认"+deliveryTag);
                });
        for (int i = 0; i < 1000; i++) {
            chanel.basicPublish("","",null,("messages"+i).getBytes());
        }
        long end = System.currentTimeMillis();
        System.out.println("异步确认使用时间："+(end-start));
    }
}
